package sms.impl;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import sms.AbstractSmsApi;
import sms.model.Result;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * ChuangLanSms
 * 测试切忌发送敏感词
 * @author Li Shuai
 * @date 15/12/21
 */
public class ChuangLanSms extends AbstractSmsApi {
    private static String URL = "http://222.73.117.156/msg/";// 应用地址

    boolean needstatus = true;// 是否需要状态报告，需要true，不需要false
    private String product = "349312826";// 产品ID
    private String extno = null;// 扩展码
    private String account = "vip-bln1";
    private String password = "Tch123456";

    private static final Log log = LogFactory.getLog(ChuangLanSms.class);


    private static Map<Byte,String> messageTemplate = new HashMap<Byte, String>();

    static{
        messageTemplate.put(MESSAGE_TEMPLATE_USER_BIND_PHONE,     "您的验证码是：【变量】，【变量】分钟内有效。");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_REGISTER,       "您的验证码是：【变量】，【变量】分钟内有效。");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_LOGIN ,         "您的验证码是：【变量】，【变量】分钟内有效。");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_REFUND,         "您的验证码是：【变量】，【变量】分钟内有效。");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_PASSWPRD_RECOVERY,"您正在找回密码,您的验证码是：【变量】，【变量】分钟内有效。");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_BINDING_YES,"您正在绑定支付账户,您的验证码是：【变量】，【变量】分钟内有效。");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_BINDING_NO,"您正在解绑支付账户,您的验证码是：【变量】，【变量】分钟内有效。");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_EXAMINE_YES,"恭喜您，您申请的【变量】达人已通过，请登录百灵鸟达人版发布活动，结识更多的百灵鸟小伙伴！");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_EXAMINE_NO,"很抱歉，您申请的【变量】达人未通过，【变量】，请登陆百灵鸟达人版更改信息!");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_REFUND_SMS,"您报名的【变量】活动已退款，退款金额【变量】元，1-3个工作日到账。订单号:【变量】。进入[我的活动]查看详情。");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_REFUND_REJECT_SMS,"非常抱歉！您提交的退款申请已被拒绝；如有疑问，请与活动负责人【变量】联系；给您带来的不便，敬请谅解。");
        messageTemplate.put(MESSAGE_TEMPLATE_BATCH_REFUND_SMS,"非常抱歉！您参加的【变量】活动由于【变量】临时取消，您支付的款项和鸟蛋将会在1-3个工作日内退款至您的原支付渠道，退款到账日期以支付宝/微信支付为准， \n" +
                "如有疑问，请拨打客服电话【变量】。");
        messageTemplate.put(MESSAGE_TEMPLATE_SIGNUP_SMS,"感谢您参与【变量】，我们将在一周内完成审核，并告知您面试时间和地点，请保持手机畅通！快把好消息告诉小伙伴吧！");
        messageTemplate.put(MESSAGE_TEMPLATE_PLACE_ORDER_NOTICE,"您已成功预订【变量】场地：【变量】详情请咨询【变量】");
        messageTemplate.put(MESSAGE_TEMPLATE_PLACE_ORDER_TICKET_NOTICE,"您已成功预订【变量】门票：【变量】详情请咨询【变量】");
        messageTemplate.put(MESSAGE_TEMPLATE_PLACE_REFUND_NOTICE,"您已成功退订【变量】场地：【变量】，退款将于三个工作日内返还。有疑问请致电【变量】");
        messageTemplate.put(MESSAGE_TEMPLATE_PLACE_BALANCE_NOTICE,"您办理的【变量】的【变量】于【变量】通过调整【变量】元至【变量】元，有疑问请致电【变量】");
        messageTemplate.put(MESSAGE_TEMPLATE_PLACE_MEMBER_CONSUME_NOTICE,"您办理的【变量】的【变量】于【变量】通过【变量】消费了【变量】，卡内剩余【变量】,可登录百灵鸟客户端查看消费明细，如非本人操作，请立即致电【变量】");
        messageTemplate.put(MESSAGE_TEMPLATE_PLACE_ADD_MEMBER_INFO,"您于【变量】成功开通【变量】的【变量】,有疑问请致电【变量】");
        messageTemplate.put(MESSAGE_TEMPLATE_PLACE_ORDER_REMIND,"客户：【变量】，通过客户端预定了【变量】场地：【变量】");
        messageTemplate.put(MESSAGE_TEMPLATE_PLACE_PROMOTION_MESSAGE,"欢迎使用百灵鸟，请点击预订链接开始订场：【变量】");
        messageTemplate.put(MESSAGE_TEMPLATE_PLACE_ADD_MEMBER_REMIND,"客户：【变量】，在【变量】，通过APP办理了【变量】的【变量】，【变量】");
        messageTemplate.put(MESSAGE_TEMPLATE_PLACE_MEMBER_RECHARGE,"客户：【变量】，在【变量】，通过APP充值了【变量】的【变量】，【变量】");
    }

    protected String getTemplateByType(Byte id) {
        return messageTemplate.get(id);
    }

    public Result sendMsg(String phone, Byte templateId, String[] args) {
        Result result = Result.returnFail(Result.SMS_SEND_FAILURE);
        try {
            String content = getTemplateByType(templateId);
            for(int i = 1; i <= args.length ; i++){
                content = content.replaceFirst("【变量】", args[i - 1]);
            }
            String str = send(URL,account,password,phone,content,true,product,null);
            String code = "0";
            if(str.indexOf("\n")>0){//成功时返回结果有换行符
                code = str.substring(str.indexOf(",")+1,str.indexOf("\n"));
            }else{
                code = str.substring(str.indexOf(",")+1,str.length());
            }
            System.out.println("code=="+code);
            switch (Integer.parseInt(code)) {
                case 0:
                    result = Result.returnSuccess(Result.SMS_SEND_SUCCESS);
                    break; //提交成功
                case 105:
                    result = Result.returnFail(Result.INCLUDE_SENSITIVE_WORD);
                    break; //短信内容含有敏感词.
                case 106:
                    result = Result.returnFail(Result.SMS_LONG_ERROR);
                    break; //手机号码长度错误
                case 107:
                    result = Result.returnFail(Result.INVALID_PHONE_NUMBER);
                    break; //手机号码错误
                case 108:
                    result = Result.returnFail(Result.SMS_MOBILE_COUNT_ERROR);
                    break; //.手机号码个数错误（>5000 || <=等于0）
                case 109:
                    result = Result.returnFail(Result.SMS_NO_TRANSMISSION_LINE);
                    break; //无发送额度.
                case 110:
                    result = Result.returnFail(Result.SMS_ERROR_SENT_TIME);
                    break; //不在发送时间内.
                case 111:
                    result = Result.returnFail(Result.SMS_SEND_TOO_OFTEN);
                    break; //超出发送次数.
                case 112:
                    result = Result.returnFail(Result.SMS_NO_PRODUCT);
                    break; //无此产品.
                case 113:
                    result = Result.returnFail(Result.SMS_ERROR_EXTNO);
                    break; //扩展码错误（不是数字或者长度不对）.
                case 115:
                    result = Result.returnFail(Result.SMS_AUTO_AUDIT_BACK);
                    break; //自动审核驳回.
                case 116:
                    result = Result.returnFail(Result.SMS_SIGN_ERROR);
                    break; //签名错误（需要签名的前提下）.
                case 117:
                    result = Result.returnFail(Result.SMS_IP_ERROR);
                    break; //IP认证失败，未登记.
                case 118:
                    result = Result.returnFail(Result.SMS_AUTHORITY_ERROR);
                    break; //权限错误.
                default:
                    result = new Result(false, Integer.parseInt(code), content);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public Result sendMsg(String[] phones, Byte templateId, String[] args) {
        if (phones == null || phones.length == 0){
            return Result.returnFail(Result.INVALID_PHONE_NUMBER);
        }
        for(int i = 0 ; i < phones.length; i++){
            sendMsg(phones[i], templateId,args);
        }
        return Result.returnSuccess(Result.SMS_SEND_SUCCESS);
    }

    /**
     *
     * @param url 应用地址，类似于http://ip:port/msg/
     * @param account 账号
     * @param pswd 密码
     * @param mobile 手机号码，多个号码使用","分割
     * @param msg 短信内容
     * @param needstatus 是否需要状态报告，需要true，不需要false
     * @return 返回值定义参见HTTP协议文档
     * @throws Exception
     */
    public static String send(String url, String account, String pswd, String mobile, String msg,
                              boolean needstatus, String product, String extno) throws Exception {
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod();
        try {
            URI base = new URI(url, false);
            method.setURI(new URI(base, "HttpBatchSendSM", false));
            method.setQueryString(new NameValuePair[] {
                    new NameValuePair("account", account),
                    new NameValuePair("pswd", pswd),
                    new NameValuePair("mobile", mobile),
                    new NameValuePair("needstatus", String.valueOf(needstatus)),
                    new NameValuePair("msg", msg),
                    new NameValuePair("product", product),
                    new NameValuePair("extno", extno),
            });
            int result = client.executeMethod(method);
            if (result == HttpStatus.SC_OK) {
                InputStream in = method.getResponseBodyAsStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = in.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                return URLDecoder.decode(baos.toString(), "UTF-8");
            } else {
                throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
            }
        } finally {
            method.releaseConnection();
        }

    }

    public static void main(String[] args) {
        ChuangLanSms chuangLanSms = new ChuangLanSms();
        Random rd = new Random();
//        rd.nextInt(10000);
        String[] str = new String[]{rd.nextInt(9999-1000+1)+1000+"","5"};
        chuangLanSms.sendMsg("13522985502",MESSAGE_TEMPLATE_USER_REGISTER,str);
    }
}
